import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:xm_app/common/logger/LoggerUtil.dart';
import 'package:xm_app/common/ui/AppTheme.dart';
import 'package:xm_app/common/ui/ui_adapter.dart';
import 'package:xm_app/model/VodDetails.dart';
import 'package:xm_app/widget/CommonText.dart';

class PlayListController extends GetxController {
  final fromIndex = 0.obs;
  final showType = 0.obs;
  final sortType = 0.obs;
  final itemIndex = 0.obs;

  setFromIndex(int index) {
    fromIndex.value = index;
    update();
  }

  setItemIndex(int index) {
    itemIndex.value = index;
    update();
  }

  selectionOnTap(bool on) {
    if (on) {
      showType.value = 1;
    } else {
      showType.value = 0;
    }
    update();
  }

  sortOnTap(bool on) {
    if (on) {
      sortType.value = 1;
    } else {
      sortType.value = 0;
    }
    update();
  }

  List<List<String>> getSourceListData(List<List<String>> sourceList) {
    if (sortType.value == 0) {
      return sourceList;
    }
    return sourceList.reversed.toList();
  }

  @override
  void onClose() {
    super.onClose();
  }
}

class PlayListWidget extends StatelessWidget {
  final bool isPlay;
  final Vod vod;
  final int fromIndex;
  final int showType;
  final int sortType;
  final int itemIndex;
  final Function(int, int) itemOnTap;
  final Function(int, int) tabOnTap;
  PlayListWidget({
    Key key,
    this.vod,
    this.fromIndex = 0,
    this.showType = 0,
    this.sortType = 0,
    this.itemIndex,
    this.itemOnTap,
    this.isPlay = false,
    this.tabOnTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle.dark,
        child: GetBuilder<PlayListController>(
          init: PlayListController()
            ..showType.value = showType
            ..sortType.value = sortType
            ..itemIndex.value = itemIndex
            ..fromIndex.value = fromIndex,
          tag: isPlay ? null : vod.vodID.toString(),
          builder: (PlayListController controller) {
            logDebug("showType ${controller.showType}");
            final sourceList = controller.getSourceListData(vod.vodPlayUrls[vod.vodPlayServer[controller.fromIndex.value].from]);
            return Column(
              children: [
                PlayListTitleWidget(
                  selectionOnTap: controller.selectionOnTap,
                  sortOnTap: controller.sortOnTap,
                ),
                SizedBox(height: 5),
                _getListPlaySource(vod.vodPlayServer, controller.fromIndex.value, (index) {
                  controller.setFromIndex(index);
                  tabOnTap?.call(index, controller.itemIndex.value);
                }),
                Divider(height: 2),
                SizedBox(height: 5),
                AnimatedCrossFade(
                  crossFadeState: controller.showType.value == 0 ? CrossFadeState.showFirst : CrossFadeState.showSecond,
                  duration: Duration(milliseconds: 500),
                  firstChild: SizedBox(
                    height: 35,
                    child: _getHorizontalListView(
                      sourceList: sourceList,
                      onTap: (index) {
                        controller.setItemIndex(index);
                        itemOnTap?.call(controller.fromIndex.value, index);
                      },
                      selectIndex: controller.itemIndex.value,
                    ),
                  ),
                  secondChild: _getGridView(
                    sourceList: sourceList,
                    onTap: (index) {
                      controller.setItemIndex(index);
                      itemOnTap?.call(controller.fromIndex.value, index);
                    },
                    selectIndex: controller.itemIndex.value,
                  ),
                ),
              ],
            );
          },
        ));
  }

  _getHorizontalListView({List<List<String>> sourceList, Function(int) onTap, int selectIndex = 0}) {
    return ListView.separated(
        scrollDirection: Axis.horizontal,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () => onTap?.call(index),
            child: Container(
              alignment: Alignment.center,
              height: getHeight(30),
              constraints: BoxConstraints(maxWidth: getWidth(80)),
              decoration: BoxDecoration(
                border: Border.all(color: selectIndex == index ? AppTheme.iconYellow : Colors.grey[200], width: 1),
                borderRadius: BorderRadius.circular(5),
              ),
              child: CommonText(sourceList[index][0], txtColor: selectIndex == index ? AppTheme.iconYellow : Colors.black),
            ),
          );
        },
        separatorBuilder: (BuildContext context, int index) {
          return SizedBox(
            width: 5,
          );
        },
        itemCount: sourceList.length);
  }

  _getGridView({List<List<String>> sourceList, Function(int) onTap, int selectIndex = 0}) {
    return GridView.builder(
      padding: EdgeInsetsDirectional.zero,
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 5,
        crossAxisSpacing: 5,
        childAspectRatio: 100 / 35,
      ),
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () => onTap?.call(index),
          child: Container(
            alignment: Alignment.center,
            height: getHeight(30),
            constraints: BoxConstraints(maxWidth: getWidth(80)),
            decoration: BoxDecoration(
              border: Border.all(color: selectIndex == index ? AppTheme.iconYellow : Colors.grey[200], width: 1),
              borderRadius: BorderRadius.circular(5),
            ),
            child: CommonText(
              sourceList[index][0],
              txtColor: selectIndex == index ? AppTheme.iconYellow : Colors.black,
            ),
          ),
        );
      },
      itemCount: sourceList.length,
    );
  }

  _getListPlaySource(List<VodPlayServer> vodPlayServer, int sIndex, Function onTap) {
    _buildItem(int index, String name, {bool isSelect = false}) {
      return GestureDetector(
        onTap: () => onTap(index),
        child: Container(
          // color: Colors.black,
          margin: EdgeInsets.symmetric(horizontal: 5, vertical: 1),
          child: Column(
            children: [
              Row(
                children: [
                  Icon(
                    Icons.play_circle_outline,
                    size: getSp(16),
                    color: isSelect ? AppTheme.iconYellow : Colors.black,
                  ),
                  SizedBox(
                    width: 2,
                  ),
                  CommonText(
                    name,
                    txtSize: getSp(13),
                    txtColor: isSelect ? AppTheme.iconYellow : Colors.black,
                  ),
                ],
              ),
              SizedBox(
                height: 5,
              ),
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(5)),
                  color: isSelect ? AppTheme.iconYellow : Colors.transparent,
                ),
                width: getWidth(65),
                height: 2,
              ),
            ],
          ),
        ),
      );
    }

    List<Widget> list = List();
    if (vodPlayServer != null && vodPlayServer.length > 0) {
      list = List.generate(vodPlayServer.length, (index) => _buildItem(index, "${vodPlayServer[index].show}", isSelect: index == sIndex));
    }

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [...list],
    );
  }
}

class PlayListTitleWidget extends StatefulWidget {
  final Function(bool) selectionOnTap;
  final Function(bool) sortOnTap;

  const PlayListTitleWidget({Key key, this.selectionOnTap, this.sortOnTap}) : super(key: key);
  @override
  _PlayListTitleWidgetState createState() => _PlayListTitleWidgetState();
}

class _PlayListTitleWidgetState extends State<PlayListTitleWidget> with TickerProviderStateMixin {
  AnimationController _selectionController;
  AnimationController _sortController;
  Animation _selectionAnimated;
  Animation _sortAnimated;
  List<String> selectionStrs = ["展开全部剧集", "收起全部剧集"];
  @override
  void initState() {
    super.initState();
    _selectionController = AnimationController(duration: Duration(microseconds: 500), vsync: this);
    _sortController = AnimationController(duration: Duration(microseconds: 500), vsync: this);
    _selectionAnimated = Tween<double>(begin: 0, end: .5).animate(_selectionController);
    _sortAnimated = Tween<double>(begin: 0, end: .5).animate(_sortController);
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        CommonText(
          "播放列表",
          txtWeight: FontWeight.w700,
          txtSize: getSp(14),
        ),
        Spacer(),
        ValueBuilder<int>(
            initialValue: 0,
            builder: (value, updateFn) {
              return GestureDetector(
                onTap: () {
                  if (_selectionAnimated.isDismissed) {
                    _selectionController.forward();
                    widget.selectionOnTap?.call(true);
                    updateFn(1);
                  } else if (_selectionAnimated.isCompleted) {
                    _selectionController.reverse();
                    updateFn(0);
                    widget.selectionOnTap?.call(false);
                  }
                },
                child: Row(
                  children: [
                    RotationTransition(
                      turns: _selectionAnimated,
                      child: Icon(
                        Icons.keyboard_arrow_down,
                        color: AppTheme.defaultIconGrey,
                      ),
                    ),
                    CommonText(selectionStrs[value])
                  ],
                ),
              );
            }),
        Container(
          color: AppTheme.defaultTxtGrey,
          height: 10,
          width: 1,
          margin: EdgeInsets.only(right: 5, left: 5),
        ),
        GestureDetector(
          onTap: () {
            if (_sortAnimated.isDismissed) {
              _sortController.forward();
              widget.sortOnTap?.call(true);
            } else if (_sortAnimated.isCompleted) {
              _sortController.reverse();
              widget.sortOnTap?.call(false);
            }
          },
          child: Row(
            children: [
              RotationTransition(
                turns: _sortAnimated,
                child: Icon(
                  Icons.sort,
                  color: AppTheme.defaultIconGrey,
                  size: getSp(18),
                ),
              ),
              CommonText("排序")
            ],
          ),
        )
      ],
    );
  }
}
